package com.yetianhua.xml;

import com.yetianhua.pojo.Configuration;
import com.yetianhua.pojo.MappedStatement;
import com.yetianhua.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yetianhua
 * @className XmlMapperBuiler
 * @description TODO
 * @date 2021/6/1
 * @time 22:11
 */
public class XmlMapperBuiler {

    public XmlMapperBuiler(Configuration configuration) {
        this.configuration = configuration;
    }

    private Configuration configuration;

    public void build(InputStream in) throws Exception {
        List<MappedStatement> mappedStatements = new ArrayList<MappedStatement>();
        Document document = new SAXReader().read(in);
        String namespace = document.getRootElement().attributeValue("namespace");
        List<Element> list = document.selectNodes("//select|//update|//delete|//insert");
        for (Element element : list) {
            String name = element.getName();
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getText();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setSqlCommandType(SqlCommandType.valueOf(name.toUpperCase()));
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            configuration.getMappedStatementMap().put(namespace + "." + id, mappedStatement);
        }
    }

    public Configuration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }
}
